package com.hivekion.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hivekion.common.exception.BusinessException;
import com.hivekion.common.scheduled.BackUpDataBaseManager;
import com.hivekion.system.domain.*;
import com.hivekion.system.domain.vo.database.SysDataBaseTableColumnVo;
import com.hivekion.system.domain.vo.database.SysDataBaseTableVo;
import com.hivekion.system.mapper.*;
import com.hivekion.system.service.ISysDataBaseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * 数据库表 业务层处理
 *
 * @author guoying
 */
@Service
public class SysDataBaseServiceImpl extends ServiceImpl<SysDataBaseMapper, SysDataBase> implements ISysDataBaseService {

    @Autowired
    private SysDataBaseMapper sysDataBaseMapper;

    @Autowired
    private BackUpDataBaseManager backUpDataBaseManager;

    @Value("${uploadPath.projectfile}")
    private String uploadPath;

    @Override
    public List<SysDataBaseTableVo> selectTableList() {
        return sysDataBaseMapper.selectTableList();
    }

    @Override
    public List<SysDataBaseTableColumnVo> selectTableColumnList(String tableName) {
        return sysDataBaseMapper.selectTableColumnList(tableName);
    }

    @Override
    public void export(String tableName, HttpServletResponse response) {
        String sqlPath = backUpDataBaseManager.exportTableDataSql(tableName);
        if (StringUtils.isNoneBlank(sqlPath)){
            File file = new File(sqlPath);
            try {
                // 输出响应正文的输出流
                OutputStream out;
                // 读取本地文件的输入流
                FileInputStream in = new FileInputStream(file);
                // 设置响应正文的MIME类型
                response.setContentType("text/plain;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment;"
                        + " filename=" + sqlPath.getBytes());
                // 把本地文件发送给客户端
                out = response.getOutputStream();
                int byteRead = 0;
                byte[] buffer = new byte[512];
                while ((byteRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, byteRead);
                }
                in.close();
                out.flush();
                out.close();
            } catch (Exception ex) {

            } finally {
                file.delete();
            }
        }else {
            throw new BusinessException(500,"导出数据库表数据错误");
        }
    }

}
